package tool

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"github.com/go-redis/redis"
	"github.com/golang/protobuf/proto"
	"github.com/vmihailenco/msgpack"
	"go.mongodb.org/mongo-driver/mongo"
	"reflect"
	"time"
)

func IsError(err error) bool {
	if err == nil {
		return false
	}
	return !reflect.ValueOf(err).IsNil()
}

func RedisError(err error) bool {
	if err == redis.Nil {
		return false
	}
	return IsError(err)
}

func MongoError(err error) bool {
	if err == mongo.ErrNoDocuments {
		return false
	}
	return IsError(err)
}

func MD5Str(s string) string {
	return MD5Bytes([]byte(s))
}

func MD5Bytes(s []byte) string {
	md5Ctx := md5.New()
	md5Ctx.Write(s)
	cipherStr := md5Ctx.Sum(nil)
	return hex.EncodeToString(cipherStr)
}

//func Atoi(str string) int {
//	i, err := strconv.Atoi(str)
//	if err != nil {
//		return 0
//	}
//	return i
//}
//
//func Atoi64(str string) int64 {
//	i, err := strconv.ParseInt(str, 10, 64)
//	if err != nil {
//		log.Error("str to int64 failed err:%v", err)
//		return 0
//	}
//	return i
//}

func ParseDBStr(str string, v proto.Message) bool {
	err := msgpack.Unmarshal([]byte(str), v)
	return err == nil
}

func DBStr(v proto.Message) string {
	data, _ := msgpack.Marshal(v)
	return string(data)
}

func RdKey(format string, args ...interface{}) string {
	return fmt.Sprintf(format, args...)
}

func GetSpaceTime(space time.Duration) int64 {
	var timeStamp = time.Now().UnixNano() / 1000000
	timeStamp = timeStamp / int64(space)
	return timeStamp
}

func UnixMs() int64 {
	return time.Now().UnixNano() / 1000000
}

func UnixSec() int64 {
	return time.Now().UnixNano() / 1000000 / 1000
}
